package com.hqyj.ctxp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.ctxp.mapper.ImageMapper;
import com.hqyj.ctxp.mapper.ShopCartMapper;
import com.hqyj.ctxp.pojo.Image;
import com.hqyj.ctxp.pojo.ShopCart;
import com.hqyj.ctxp.service.ImageService;
import com.hqyj.ctxp.service.ShopCartService;
import com.hqyj.ctxp.utils.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class ShopCartServiceImpl extends ServiceImpl<ShopCartMapper, ShopCart> implements ShopCartService {

    @Autowired
    private ShopCartMapper shopCartMapper;

    //添加到购物车
    @Override
    @Transactional
    public ResultInfo addCart(ShopCart shopCart) {
        int num = shopCartMapper.insert(shopCart);
        if(num>0){
            return new ResultInfo(200,"已加入购物车");
        }
        return new ResultInfo(500,"加入失败");
    }

    //更新数量
    @Override
    public ResultInfo updateNum(ShopCart shopCart) {
        QueryWrapper<ShopCart> wrapper = new QueryWrapper<ShopCart>()
                .eq("product_id", shopCart.getProductId())
                .eq("user_no", shopCart.getUserNo());
        ShopCart cart1 = shopCartMapper.selectOne(wrapper);
        UpdateWrapper<ShopCart> wrapper1 = new UpdateWrapper<ShopCart>().eq("product_id", cart1.getProductId())
                .eq("user_no", shopCart.getUserNo())
                .set("number", (shopCart.getNumber()+cart1.getNumber()));
        int num = shopCartMapper.update(null, wrapper1);
        if(num>0){
            return new ResultInfo(200,"已更新商品数量");
        }
        return new ResultInfo(500,"商品数量更新失败");
    }


    //查看当前用户的购物车
    @Override
    public ResultInfo showUserCart(Integer userNo) {
        List<ShopCart> shopCarts = shopCartMapper.showCarts(userNo);
        return  new ResultInfo(200,"查询成功",shopCarts);
    }

    //删除商品
    @Override
    public ResultInfo deleteProduct(ShopCart shopCart) {
        QueryWrapper<ShopCart> wrapper = new QueryWrapper<ShopCart>().eq("product_id", shopCart.getProductId())
                .eq("user_no", shopCart.getUserNo());
        int num = shopCartMapper.delete(wrapper);
        if(num>0){
            return new ResultInfo(200,"删除成功");
        }
        return new ResultInfo(500,"删除失败");
    }

}
